﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Cocon90.Lib.Util
{

    /// <summary>
    /// 用来重复执行某事
    /// </summary>
    public class IntervalInvoker
    {
        /// <summary>
        /// 创建一个新实例，如果想无限次数执行下去，请把count参数传为int.MaxValue
        /// </summary>
        /// <param name="interval"></param>
        /// <returns></returns>
        public static IntervalInvoker CreateInstence(int interval, int count)
        {
            return new IntervalInvoker(interval, count);
        }
        /// <summary>
        ///获取或设置 每次执行后间隔多长时间再执行（调用Invoke方法前配置此属性才生效）
        /// </summary>
        public int Interval { get; set; }
        /// <summary>
        /// 获取或设置 总执行次数
        /// </summary>
        public int Count { get; set; }
        public int CurrentCount { get; set; }
        /// <summary>
        /// 定义多少毫秒的延时，以及执行次数
        /// </summary>
        /// <param name="interval"></param>
        IntervalInvoker(int interval, int count)
        {
            this.Interval = interval;
            this.Count = count;
        }
        /// <summary>
        /// 间隔Interval毫秒后开始执行某事，第二参指定是否在调用Invoke的瞬间就执行一次action（默认为false）
        /// </summary>
        /// <param name="action"></param>
        public void Invoke(Action action, bool isActionStart = false, Action finishAction = null)
        {
            CurrentCount = 0;
            if (isActionStart) { action(); CurrentCount++; }
            System.Timers.Timer th = new System.Timers.Timer(this.Interval);
            th.Elapsed += (s, e) =>
            {
                CurrentCount++;

                if (Count <= CurrentCount)
                {
                    if (Count != int.MaxValue)
                    { th.Stop(); if (finishAction != null) { finishAction(); } }
                }
                action();
            };
            th.Start();
        }
    }

}
